package com.yanfan.energybilling.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.yanfan.community.building.domain.CommunityBuilding;
import com.yanfan.community.building.mapper.CommunityBuildingMapper;
import com.yanfan.energybilling.domain.vo.GroupByEnergyTypeVo;
import com.yanfan.energybilling.service.EnergyManagementDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Component
public class EnergyManagementDashboardServiceImpl implements EnergyManagementDashboardService {

    @Autowired
    private TDEnergyDeductionRecordServiceImpl tdEnergyDeductionRecordService;
    @Autowired
    private CommunityBuildingMapper communityBuildingMapper;



    @Override
    public Map<String, JSONObject> totalDifferenceValueGroupByEnergyType() {
        Map<String, JSONObject> resultMap = new HashMap<>();
        LocalDate now = LocalDate.now();
        //把now 格式化为yyyy-mm-dd
        String nowStr = now.toString();
        //获取昨天的日期
        String yesterday = now.minusDays(1).toString();
        //获取明天的日期
        String tomorrow = now.plusDays(1).toString();
        //获取总用量
        List<GroupByEnergyTypeVo> totalList = tdEnergyDeductionRecordService.totalDifferenceValueGroupByEnergyType(null,null);
        //获取今日用量
        List<GroupByEnergyTypeVo> todayList = tdEnergyDeductionRecordService.totalDifferenceValueGroupByEnergyType(nowStr+" 00:00:00",tomorrow+" 00:00:00");
        //获取昨日用量
        List<GroupByEnergyTypeVo> yesterdayList = tdEnergyDeductionRecordService.totalDifferenceValueGroupByEnergyType(yesterday+" 00:00:00",nowStr+" 00:00:00");
        JSONObject totalObj = new JSONObject();
        JSONObject todayObj = new JSONObject();
        JSONObject yesterdayObj = new JSONObject();
        if (CollectionUtil.isEmpty(totalList) && CollectionUtil.isEmpty(todayList) && CollectionUtil.isEmpty(yesterdayList)){
            resultMap.put("total", totalObj.fluentPut("water", BigDecimal.ZERO).fluentPut("electricity", BigDecimal.ZERO).fluentPut("gas", BigDecimal.ZERO));
            resultMap.put("today", todayObj.fluentPut("water", BigDecimal.ZERO).fluentPut("electricity", BigDecimal.ZERO).fluentPut("gas", BigDecimal.ZERO));
            resultMap.put("yesterday", yesterdayObj.fluentPut("water", BigDecimal.ZERO).fluentPut("electricity", BigDecimal.ZERO).fluentPut("gas", BigDecimal.ZERO));
            return resultMap;
        }
        for (GroupByEnergyTypeVo groupByEnergyTypeVo : totalList) {
            switch (groupByEnergyTypeVo.getEnergyGroup()) {
                case "水":
                    totalObj.fluentPut("water", groupByEnergyTypeVo.getTotalEnergy());
                    break;
                case "电":
                    totalObj.fluentPut("electricity", groupByEnergyTypeVo.getTotalEnergy());
                    break;
                case "气":
                    totalObj.fluentPut("gas", groupByEnergyTypeVo.getTotalEnergy());
                    break;
            }
        }
        for (GroupByEnergyTypeVo groupByEnergyTypeVo : todayList) {
            switch (groupByEnergyTypeVo.getEnergyGroup()) {
                case "水":
                    todayObj.fluentPut("water", groupByEnergyTypeVo.getTotalEnergy());
                    break;
                case "电":
                    todayObj.fluentPut("electricity", groupByEnergyTypeVo.getTotalEnergy());
                    break;
                case "气":
                    todayObj.fluentPut("gas", groupByEnergyTypeVo.getTotalEnergy());
                    break;
            }
        }
        for (GroupByEnergyTypeVo groupByEnergyTypeVo : yesterdayList) {
            switch (groupByEnergyTypeVo.getEnergyGroup()) {
                case "水":
                    yesterdayObj.fluentPut("water", groupByEnergyTypeVo.getTotalEnergy());
                    break;
                case "电":
                    yesterdayObj.fluentPut("electricity", groupByEnergyTypeVo.getTotalEnergy());
                    break;
                case "气":
                    yesterdayObj.fluentPut("gas", groupByEnergyTypeVo.getTotalEnergy());
                    break;
            }
        }
        resultMap.put("total", totalObj);
        resultMap.put("today", todayObj);
        resultMap.put("yesterday", yesterdayObj);
        return resultMap;
    }

    @Override
    public JSONObject echarts(String timeType, String energyType,List<String> deviceNames) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        LocalDate now = LocalDate.now();
        //获取明天的日期
        String tomorrow = now.plusDays(1).toString();
        JSONObject resultObj = new JSONObject();
        List<String> energyTypeList = CollectionUtil.newArrayList();
        switch (energyType){
            case "水":
                energyTypeList=CollectionUtil.newArrayList("1","2","3");
                break;
            case "电":
                energyTypeList=CollectionUtil.newArrayList("7");
                break;
            case "气":
                energyTypeList=CollectionUtil.newArrayList("4","5","6");
                break;
        }
        List<GroupByEnergyTypeVo> data=CollectionUtil.newArrayList();
        switch (timeType){
            case "day":
                data = tdEnergyDeductionRecordService.buildEcharts(timeType,energyTypeList, now.toString()+" 00:00:00", tomorrow.toString()+" 00:00:00",deviceNames);
                if (CollectionUtil.isEmpty(data)){
                    return resultObj.fluentPut("data", CollectionUtil.newArrayList())
                            .fluentPut("xAxis", IntStream.rangeClosed(0, 23)
                            .mapToObj(hour -> hour)
                            .collect(Collectors.toList()));
                }
                resultObj.put("xAxis", data.stream().map(item ->
                        item.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().getHour()
                ).collect(Collectors.toList()));
                break;
            case "month":
                //获取当月的第一天
                LocalDate firstDay = now.withDayOfMonth(1);
                //获取当月的天数
                int daysInMonth = now.lengthOfMonth();
                //获取下月的第一天
                LocalDate nextFirstDay = firstDay.plusMonths(1);
                data = tdEnergyDeductionRecordService.buildEcharts(timeType,energyTypeList, firstDay.toString()+" 00:00:00", nextFirstDay.toString()+" 00:00:00",deviceNames);
                if (CollectionUtil.isEmpty(data)){
                    return resultObj.fluentPut("data", CollectionUtil.newArrayList())
                            .fluentPut("xAxis", IntStream.rangeClosed(1, daysInMonth)
                                    .mapToObj(day -> day)
                                    .collect(Collectors.toList()));
                }
                resultObj.put("xAxis", data.stream().map(item ->
                        item.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().getDayOfMonth()
                ).collect(Collectors.toList()));
                break;
            case "year":
                data = tdEnergyDeductionRecordService.buildEcharts(timeType,energyTypeList, now.getYear()+"-01-01 00:00:00", (now.getYear()+1)+"-01-01 00:00:00",deviceNames);
                if (CollectionUtil.isEmpty(data)){
                    return resultObj.fluentPut("data", CollectionUtil.newArrayList())
                            .fluentPut("xAxis", IntStream.rangeClosed(1, 12)
                                    .mapToObj(month -> month)
                                    .collect(Collectors.toList()));
                }
                resultObj.put("xAxis", data.stream().map(item ->
                        item.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().getMonth().getValue()
                ).collect(Collectors.toList()));
                break;
        }
        resultObj.put("data", data.stream().map(item -> item.getTotalEnergy()).collect(Collectors.toList()));
        return resultObj;
    }

    @Override
    public List<GroupByEnergyTypeVo> regionalEnergyConsumption() {
        //获取每个区域下的总电能
        List<GroupByEnergyTypeVo> groupByEnergyTypeVoList = tdEnergyDeductionRecordService.sumDifferenceValueGroupByBuilding("7");
        if (CollectionUtil.isEmpty(groupByEnergyTypeVoList)){
            return CollectionUtil.newArrayList();
        }
        //获取总电能
        BigDecimal totalValue = groupByEnergyTypeVoList.stream().map(item -> BigDecimal.valueOf(Double.parseDouble(item.getValue()))).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, RoundingMode.HALF_UP);
        if (totalValue.compareTo(BigDecimal.ZERO) == 0){
            // 创建新集合存储有效数据
            List<GroupByEnergyTypeVo> validList = new ArrayList<>();
            for (GroupByEnergyTypeVo groupByEnergyTypeVo : groupByEnergyTypeVoList) {
                CommunityBuilding communityBuilding = communityBuildingMapper.selectSysBuildingByBuildingId(Long.valueOf(groupByEnergyTypeVo.getBuildingId()));
                if (!ObjectUtil.isEmpty(communityBuilding)){
                    groupByEnergyTypeVo.setName(communityBuilding.getBuildingName());
                    validList.add(groupByEnergyTypeVo);
                }
            }
            if (CollectionUtil.isNotEmpty(validList)){
                for (GroupByEnergyTypeVo groupByEnergyTypeVo : validList){
                    BigDecimal proportion = BigDecimal.valueOf(100)
                            .divide(new BigDecimal(validList.size()), 2, RoundingMode.HALF_UP);
                    groupByEnergyTypeVo.setProportion(proportion);
                }
                return validList;
            }
            return CollectionUtil.newArrayList();
        }
        //为了防止区域修改删除，取mysql的区域名称
        List<GroupByEnergyTypeVo> validList = new ArrayList<>();
        for (GroupByEnergyTypeVo groupByEnergyTypeVo : groupByEnergyTypeVoList) {
            CommunityBuilding communityBuilding = communityBuildingMapper.selectSysBuildingByBuildingId(Long.valueOf(groupByEnergyTypeVo.getBuildingId()));
            if (!ObjectUtil.isEmpty(communityBuilding)){
                groupByEnergyTypeVo.setName(communityBuilding.getBuildingName());
                validList.add(groupByEnergyTypeVo);
            }
        }
        if (CollectionUtil.isNotEmpty(validList)){
            for (GroupByEnergyTypeVo groupByEnergyTypeVo : validList) {
                BigDecimal proportion = BigDecimal.valueOf(100)
                        .divide(new BigDecimal(validList.size()), 2, RoundingMode.HALF_UP);
                groupByEnergyTypeVo.setProportion(proportion);
            }
        }
        return validList;
    }

}
